import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:playtruly/common/models/index.dart';
import '../../../../common/utils/toast_util.dart';
import 'activity_application_management_controller.dart';

/// 活动申请用户管理页面
class ActivityApplicationManagementPage extends GetView<ActivityApplicationManagementController> {
  const ActivityApplicationManagementPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFD94841),
      appBar: AppBar(
        leading: IconButton(
          onPressed: () {
            Get.back();
          },
          icon: const Icon(Icons.arrow_back_ios_new_outlined),
        ),
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: const Text(
          '活动申请用户管理',
          style: TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: true,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: GetBuilder<ActivityApplicationManagementController>(
        init: ActivityApplicationManagementController(),
        builder: (controller) {
          return Obx(() {
            if (controller.isLoading) {
              return const Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    CircularProgressIndicator(
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                    ),
                    SizedBox(height: 16),
                    Text(
                      '加载中...',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
              );
            }

            final participants = controller.sortedParticipants;

            if (participants.isEmpty) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.people_outline,
                      size: 80,
                      color: Colors.white.withOpacity(0.5),
                    ),
                    const SizedBox(height: 16),
                    Text(
                      '暂无申请用户',
                      style: TextStyle(
                        color: Colors.white.withOpacity(0.8),
                        fontSize: 18,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      '当前没有用户申请加入您的活动',
                      style: TextStyle(
                        color: Colors.white.withOpacity(0.6),
                        fontSize: 14,
                      ),
                    ),
                  ],
                ),
              );
            }

            return RefreshIndicator(
              onRefresh: () => controller.refreshParticipants(),
              child: ListView.builder(
                padding: const EdgeInsets.all(16.0),
                itemCount: participants.length,
                itemBuilder: (context, index) {
                  final participant = participants[index];
                  return _buildUserCard(participant);
                },
              ),
            );
          });
        },
      ),
    );
  }

  /// 显示操作底部菜单
  void _showActionBottomSheet(PublisherParticipantsData participant) {
    showModalBottomSheet(
      context: Get.context!,
      backgroundColor: Colors.transparent,
      builder: (context) {
        return Container(
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 顶部拖拽条
              Container(
                margin: const EdgeInsets.only(top: 12, bottom: 8),
                width: 40,
                height: 4,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
              
              // 用户信息
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                child: Row(
                  children: [
                    GestureDetector(
                      onTap: () => controller.goToUserProfile(participant), // 🎯 点击头像跳转到用户信息页面
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(20),
                        child: Image.network(
                          participant.userAvatarUrl ?? controller.getDefaultAvatarUrl(),
                          width: 40,
                          height: 40,
                          fit: BoxFit.cover,
                          errorBuilder: (context, error, stackTrace) {
                            return Container(
                              width: 40,
                              height: 40,
                              decoration: BoxDecoration(
                                color: Colors.grey[300],
                                borderRadius: BorderRadius.circular(20),
                              ),
                              child: const Icon(Icons.person, size: 20),
                            );
                          },
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '${participant.userName} 申请加入活动',
                            style: const TextStyle(
                              fontSize: 14,
                              color: Colors.black87,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                            decoration: BoxDecoration(
                              color: const Color(0xFFD94841).withOpacity(0.1),
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: Text(
                              '活动：${participant.activityName}',
                              style: const TextStyle(
                                fontSize: 12,
                                color: Color(0xFFD94841),
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              
              const Divider(height: 1),
              
              // 操作选项
              ListTile(
                leading: const Icon(Icons.check_circle, color: Colors.green),
                title: const Text('同意'),
                onTap: () {
                  Navigator.pop(context);
                  controller.approveApplication(participant);
                },
              ),
              
              ListTile(
                leading: const Icon(Icons.cancel, color: Colors.red),
                title: const Text('拒绝'),
                onTap: () {
                  Navigator.pop(context);
                  controller.rejectApplication(participant);
                },
              ),
              
              ListTile(
                leading: const Icon(Icons.report, color: Colors.orange),
                title: const Text('举报'),
                onTap: () {
                  Navigator.pop(context);
                  ToastUtil.info('举报功能开发中...');
                },
              ),
              
              const SizedBox(height: 16),
            ],
          ),
        );
      },
    );
  }

  /// 根据性别获取图标
  IconData _getGenderIcon(String? gender) {
    switch (gender) {
      case '男':
        return Icons.male;
      case '女':
        return Icons.female;
      default:
        return Icons.help_outline; // 未知性别使用问号图标
    }
  }

  /// 构建用户卡片
  Widget _buildUserCard(PublisherParticipantsData participant) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16.0),
      child: Stack(
        children: [
          GestureDetector(
            onLongPress: participant.isPending ? () => _showActionBottomSheet(participant) : null,
            child: Card(
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
              elevation: 4,
              child: Container(
                padding: const EdgeInsets.all(16.0),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(16),
                ),
                child: Column(
                  children: [
                    Row(
                      children: [
                        // 头像
                        GestureDetector(
                          onTap: () => controller.goToUserProfile(participant), // 🎯 点击头像跳转到用户信息页面
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(30),
                            child: Image.network(
                              participant.userAvatarUrl ?? controller.getDefaultAvatarUrl(),
                              width: 60,
                              height: 60,
                              fit: BoxFit.cover,
                              errorBuilder: (context, error, stackTrace) {
                                return Container(
                                  width: 60,
                                  height: 60,
                                  decoration: BoxDecoration(
                                    color: Colors.grey[300],
                                    borderRadius: BorderRadius.circular(30),
                                  ),
                                  child: const Icon(Icons.person, size: 30),
                                );
                              },
                            ),
                          ),
                        ),
                        const SizedBox(width: 16),
                        
                        // 用户信息
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // 姓名和等级标签
                              Row(
                                children: [
                                  Text(
                                    participant.userName,
                                    style: const TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.black87,
                                    ),
                                  ),
                                  const SizedBox(width: 8),
                                  Container(
                                    padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                                    decoration: BoxDecoration(
                                      color: Colors.red,
                                      borderRadius: BorderRadius.circular(8),
                                    ),
                                    child: Text(
                                      controller.getUserLevelText(participant.userLevel), // userLevel实际存储的是积分
                                      style: const TextStyle(
                                        color: Colors.white,
                                        fontSize: 10,
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 4),
                              
                              // 🔥 修改：性别和年龄（使用生日计算年龄）
                              Row(
                                children: [
                                  Icon(
                                    _getGenderIcon(participant.userGender),
                                    size: 14,
                                    color: Colors.grey[600],
                                  ),
                                  const SizedBox(width: 4),
                                  Text(
                                    '${participant.userGender ?? '未知'} | ${controller.calculateAgeFromBirthday(participant.userBirthday)}岁',
                                    style: TextStyle(
                                      color: Colors.grey[600],
                                      fontSize: 12,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 4),
                              
                              // 描述/签名
                              Text(
                                participant.userSignature ?? '这个人很懒，什么都没留下',
                                style: TextStyle(
                                  color: Colors.grey[700],
                                  fontSize: 14,
                                ),
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ],
                          ),
                        ),
                        
                        // 状态和操作
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            // 操作图标
                            if (participant.isPending)
                              GestureDetector(
                                onTap: () => _showActionBottomSheet(participant),
                                child: Container(
                                  padding: const EdgeInsets.all(8),
                                  decoration: BoxDecoration(
                                    color: Colors.grey[100],
                                    borderRadius: BorderRadius.circular(12),
                                  ),
                                  child: Icon(
                                    Icons.more_horiz,
                                    size: 20,
                                    color: Colors.grey[600],
                                  ),
                                ),
                              )
                            else if (participant.isApproved)
                              Icon(
                                Icons.check_circle,
                                size: 20,
                                color: Colors.green[400],
                              )
                            else if (participant.isRejected)
                              // 🔥 修复：为已拒绝状态显示取消图标
                              Icon(
                                Icons.cancel,
                                size: 20,
                                color: Colors.red[400],
                              )
                            else
                              Icon(
                                Icons.help_outline,
                                size: 20,
                                color: Colors.grey[400],
                              ),
                            const SizedBox(height: 8),
                            
                            // 状态标签
                            if (participant.isPending)
                              Container(
                                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                                decoration: BoxDecoration(
                                  color: Colors.orange,
                                  borderRadius: BorderRadius.circular(12),
                                ),
                                child: const Text(
                                  '待审核',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 12,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              )
                            else if (participant.isApproved)
                              Container(
                                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                                decoration: BoxDecoration(
                                  color: Colors.green,
                                  borderRadius: BorderRadius.circular(12),
                                ),
                                child: const Text(
                                  '已通过',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 12,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              )
                            else if (participant.isRejected)
                              // 🔥 修复：添加已拒绝状态的显示
                              Container(
                                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                                decoration: BoxDecoration(
                                  color: Colors.red,
                                  borderRadius: BorderRadius.circular(12),
                                ),
                                child: const Text(
                                  '已拒绝',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 12,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ),
                          ],
                        ),
                      ],
                    ),
                    
                    // 🔥 活动申请信息（所有状态都显示）
                    const SizedBox(height: 16),
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: participant.isPending 
                            ? Colors.black87 
                            : participant.isApproved 
                                ? Colors.green.withOpacity(0.8)
                                : Colors.red.withOpacity(0.8),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Row(
                        children: [
                          // 左侧申请信息（根据状态显示不同文字）
                          Expanded(
                            child: Text(
                              participant.isPending 
                                  ? '申请加入「${participant.activityName}」'
                                  : participant.isApproved 
                                      ? '已通过加入「${participant.activityName}」'
                                      : '被拒绝加入「${participant.activityName}」',
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 14,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                          
                          const SizedBox(width: 12),
                          
                          // 中间的活动文字
                          const Text(
                            '活动',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 12,
                            ),
                          ),
                          
                          const SizedBox(width: 12),
                          
                          // 右侧时间
                          Text(
                            controller.formatApplicationTime(participant.applicationTime),
                            style: TextStyle(
                              color: Colors.grey[300],
                              fontSize: 12,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          
          // 审核中的遮罩
          if (controller.isReviewing)
            Positioned.fill(
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.3),
                  borderRadius: BorderRadius.circular(16),
                ),
                child: const Center(
                  child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }
}